<?php
namespace app\common\lib;

class Cookie{

	static $secret='wxmax@100';

	/**
	 * 写缓存
	 * @param [type] $cookie_name [description]
	 * @param [type] $data        [description]
	 */
	public static function add($cookie_name,$data=[]){
		if(empty($data)){
			return false;
		}
		// 加入缓存生成时间
		$data['cookie_time'] = time();

		$data_str = self::arrayToStr($data);
		$token = self::genToken($data);
		// 组合缓存字符串
		$cookie_str = $data_str.'token|||'.$token;

		setcookie($cookie_name, $cookie_str,0,'/');
	}

	/**
	 * 读缓存
	 * @param  [type] $cookie_name [description]
	 * @return [type]              [description]
	 */
	public static function get($cookie_name){

		if(!isset($_COOKIE[$cookie_name])){
			return false;
		}else{
			$cookie = $_COOKIE[$cookie_name];
			$array = explode('###', $cookie);
			$data = [];
			foreach($array as $value):
				$arr = explode('|||',$value);
				$data[$arr[0]] = $arr[1];
			endforeach;
			$token = $data['token'];
			unset($data['token']);
			if(false===self::checkToken($data,$token)){
				return false;
			}else{
				// 去除缓存生成时间
				unset($data['cookie_time']);
				return $data;
			}
		}
	}

	/**
	 * 验证令牌
	 * @param  [type] $array [description]
	 * @param  [type] $token [description]
	 * @return [type]        [description]
	 */
	public static function checkToken($array,$token){
		$hash = self::genToken($array);
		if($token!=$hash){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * 数组处理
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function arrayToStr($data){
		ksort($data);
		$str = '';
		foreach($data as $key => $value):
			$str .= $key.'|||'.$value.'###';
		endforeach;
		return $str;
	}

	/**
	 * 生成令牌
	 * @return [type] [description]
	 */
	public static function genToken($array){
		return md5(self::arrayToStr($array).self::$secret);
	}

}